package com.dz.controller.user;

import com.dz.constant.RedisConstant;
import com.dz.enumeration.AppHttpCodeEnum;
import com.dz.redis.RedisCache;
import com.dz.result.Result;
import com.dz.service.DishService;
import com.dz.vo.DishVO;
import io.jsonwebtoken.lang.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 鄧浩奇
 * @classname UserDishCOntroller
 * @description
 * @since 2024/1/7 16:23
 **/

@Api(tags = "C端菜品接口")
@RestController
@RequestMapping("/user/dish")
public class UserDishController {

    private final DishService dishService;

    private final RedisCache redisCache;

    @Autowired
    public UserDishController(DishService dishService, RedisCache redisCache) {
        this.dishService = dishService;
        this.redisCache = redisCache;
    }

    @ApiOperation("C端菜品浏览")
    @GetMapping("/list")
    public Result<List<DishVO>> list(Long categoryId) {
        Assert.notNull(categoryId, AppHttpCodeEnum.CATEGORY_ID_IS_NULL.getMsg());
        String redisKey = RedisConstant.DISH_ + categoryId;
        // 判断缓存有无数据
        List<DishVO> dishCache = redisCache.getCacheList(redisKey);// Dish_101
        redisCache.expire(redisKey, RedisConstant.TIME_OUT_ONE_DAY, TimeUnit.DAYS); // 设置过期时间为1天
        if (!dishCache.isEmpty()) {
            // 有数据直接返回
            return Result.success(dishCache);
        }
        // 无数据 查询数据库
        List<DishVO> list = dishService.getDishVoByCategoryId(categoryId);

        // 存入Redis
        if (!list.isEmpty()) {
            redisCache.setCacheList(redisKey, list);
        }

        return Result.success(list);
    }
}
